package com.bstek.uflo.samplecenter;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.model.task.TaskState;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.StartProcessInfo;
import com.bstek.uflo.service.TaskService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class TestController {
	@Resource(name=TaskService.BEAN_ID)
	private TaskService taskService;
	@Resource(name=ProcessService.BEAN_ID)
	private ProcessService processService;
	@RequestMapping("/startPi")
	@ResponseBody
	@Transactional
	public void startProcessInstance(@RequestParam Map<String,Object>params) {
		Object piCount=params.get("piCount");
		if(piCount==null) {
			piCount="1";
		}
		String processIdObj=(String) params.get("processId");
		int count=Integer.parseInt((String) piCount);
		for(int i=0;i<count;i++) {
			System.out.println(i);
			new Thread(new Runnable() {

				@Override
				public void run() {
					long processId = Long.parseLong(processIdObj);
					StartProcessInfo startProcessInfo = new StartProcessInfo();
					startProcessInfo.setPromoter("user1");
					processService.startProcessById(processId, startProcessInfo);
				}
				
			}).start();
		}
	}
	@RequestMapping("/startPi2")
	@ResponseBody
	@Transactional
	public void startProcessInstance2(@RequestParam Map<String,Object>params) {
		Object piCount=params.get("piCount");
		if(piCount==null) {
			piCount="1";
		}
		String processIdObj=(String) params.get("processId");
		int count=Integer.parseInt((String) piCount);
		for(int i=0;i<count;i++) {
			System.out.println(i);
			long processId = Long.parseLong(processIdObj);
			StartProcessInfo startProcessInfo = new StartProcessInfo();
			startProcessInfo.setPromoter("user1");
			processService.startProcessById(processId, startProcessInfo);
		}
	}
	@RequestMapping("/completeTask")
	@ResponseBody
	@Transactional
	public Map<String, Object> completeTask(@RequestParam Map<String,Object>params) {
		String cpType=(String) params.get("cpType");//complete完成当前节点simple
		if("simple".contentEquals(cpType)) {
			return cpSimple(params);
		} else if("appoint".contentEquals(cpType)){
			return cpAppointNext(params);
		} else if("parti".contentEquals(cpType)){
			return cpParti(params);
		} else if("circulation".contentEquals(cpType)){
			return cpCirculateNext(params);
		} else {
			return cpSimple(params);
		}
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/completeTask2")
	@ResponseBody
	@Transactional
	public Map<String, Object> completeTask2(@RequestParam Map<String,Object>params) {
		String taskIdsStr=(String) params.get("taskIds");
		String vars=(String) params.get("vars");
		String taskIds[]=taskIdsStr.split(",");
		Map<String,Object> varsMap=new HashMap<String,Object>();
		ObjectMapper mapper=new ObjectMapper();
		try {
			List<Map<String,Object>> list=mapper.readValue(vars, List.class);
			Map<String, Object>temp=list.get(0);
			varsMap.put((String) temp.get("key"), temp.get("value"));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		for(String taskId:taskIds) {
			taskService.complete(Long.parseLong(taskId),varsMap);
		}
		return params;
	}
	@RequestMapping("/getTaskIdsByProcessId")
	@ResponseBody
	public Map<String, Object> getTaskIdsByProcessId(@RequestParam Map<String,Object>params) {
		String processId=(String) params.get("processId");//complete完成当前节点simple
		Map<String,Object> rsMap=new HashMap<String,Object>();
		List<Task> taskList=taskService.createTaskQuery().processId(Long.parseLong(processId)).addTaskState(TaskState.Created).addTaskState(TaskState.InProgress).list();
		Set<String> ids=new HashSet<String>();
		taskList.forEach((t)->{
			ids.add(""+t.getId());
		});
		rsMap.put("taskIds", StringUtils.join(ids, ","));
		return rsMap;
	}
	private Map<String,Object> cpParti(Map<String, Object> params) {
		Map<String,Object> rsMap=new HashMap<String,Object>();
		String tName=(String)params.get("tName");
		List<Task> taskList=null;
		taskList=taskService.createTaskQuery().addTaskState(TaskState.Ready).nodeName(tName).list();
		int taskSize=taskList.size();
		if(taskList.size()>25) {
		}
		rsMap.put("taskCount", taskSize);
//		taskSize=2;
		for(Task t:taskList.subList(0, taskSize)) {
			params.put("i", ""+t.getId());
			new Thread(new Runnable() {
				String taskIdStr=(String) params.get("i");
				@Override
				public void run() {
					long taskId = Long.valueOf(taskIdStr);
					taskService.claim(taskId, "user2");
					taskService.complete(taskId);
				}
				
			}).start();
		}
		return rsMap;
	}
	private Map<String,Object> cpSimple(Map<String, Object> params) {
		String tName=(String)params.get("tName");
		List<Task> taskList=taskService.createTaskQuery().addTaskState(TaskState.Created).nodeName(tName).list();
		int taskSize=taskList.size();
		if(taskList.size()>25) {
			//taskSize=80;
		}
		Map<String,Object> rsMap=new HashMap<String,Object>();
		rsMap.put("taskCount", taskSize);
		for(Task t:taskList.subList(0, taskSize)) {
			params.put("i", ""+t.getId());
			new Thread(new Runnable() {
				String taskIdStr=(String) params.get("i");
				@Override
				public void run() {
					System.out.println(taskIdStr);
					long taskId = Long.valueOf(taskIdStr);
					taskService.complete(taskId);
				}
				
			}).start();
		}
		return rsMap;
	}
	private Map<String,Object> cpAppointNext(Map<String, Object> params) {
		String tName=(String)params.get("tName");
		List<Task> taskList=taskService.createTaskQuery().addTaskState(TaskState.Created).nodeName("人工任务"+tName).list();
		int taskSize=taskList.size();
		if(taskList.size()>25) {
			//taskSize=1;
		}
		Map<String,Object> rsMap=new HashMap<String,Object>();
		rsMap.put("taskCount", taskSize);
		for(Task t:taskList.subList(0, taskSize)) {
			params.put("i", ""+t.getId());
			new Thread(new Runnable() {
				String taskIdStr=(String) params.get("i");
				@Override
				public void run() {
					long taskId = Long.valueOf(taskIdStr);
					String assignees[]= {"user1", "user2"};
					String taskNodeName="人工任务"+(Integer.parseInt(tName)+1);
					taskService.saveTaskAppointor(taskId, assignees, taskNodeName);
//					taskService.claim(taskId, "user2");
					taskService.complete(taskId);
				}
			}).start();
		}
		return rsMap;
	}
	private Map<String,Object> cpCirculateNext(Map<String, Object> params) {
		String tName=(String)params.get("tName");
		List<Task> taskList=taskService.createTaskQuery().addTaskState(TaskState.Created).nodeName("人工任务"+tName).list();
		int taskSize=taskList.size();
		if(taskList.size()>25) {
			//taskSize=1;
		}
		Map<String,Object> rsMap=new HashMap<String,Object>();
		rsMap.put("taskCount", taskSize);
		for(Task t:taskList.subList(0, taskSize)) {
			params.put("i", ""+t.getId());
			new Thread(new Runnable() {
				String taskIdStr=(String) params.get("i");
				@Override
				public void run() {
					long taskId = Long.valueOf(taskIdStr);
					String assignees[]= {"user1", "user2"};
					String taskNodeName="人工任务"+(Integer.parseInt(tName)+1);
					taskService.saveTaskPassersby(taskId, "http://www.baidu.com", assignees, taskNodeName);
//					taskService.claim(taskId, "user2");
					taskService.complete(taskId);
				}
			}).start();
		}
		return rsMap;
	}
	@RequestMapping("/")
	public String indexForward() {
		return "redirect:/index.html";
	}
	@RequestMapping("/test.f")
	@Transactional(rollbackFor = Exception.class)
	public ModelAndView test() {
		transcation1();
		return null;
	}
	//@Transactional
	public void transcation1() {
		datasource1();
	}
	public void transcation2() {
		//datasource1();
	}
	@Transactional
	@RequestMapping("/trans.f")
	public void transcation3() {
		long taskId=226405;//,,
		taskService.complete(taskId);
		long taskId2=226404;
		taskService.complete(taskId2);
	}
	@Resource(name = "dataSource")
	private DataSource dataSource1;
	
	public void datasource1() {
		NamedParameterJdbcTemplate  jdbcTemplate = new NamedParameterJdbcTemplate (dataSource1);
		jdbcTemplate.query("select * from UFLO_BLOB", new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				System.out.println(rs.getString(1)+","+rs.getString(3));
			}
		});
		jdbcTemplate.update("INSERT INTO UFLO_BLOB(id_,name_,process_id_) VALUES('19','test9-1','22')", new HashMap<String, Object>());
//		jdbcTemplate.update("INSERT INTO UFLO_BLOB(id_,name_,process_id_) VALUES('15','test9-2','21')", new HashMap());
		if(true) throw new RuntimeException("test");
	}
}
